"""
用户账户相关功能：注册、短信、登录、注销
"""
import uuid
import datetime
from web import models
from io import BytesIO
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
import random
import redis
from django_redis import get_redis_connection
import json
from utils.alicloud.sms import send_sms
from django.conf import settings
from web.forms.account import RegisterModelForm, LoginSmsForm, LoginForm
from web.forms.sms import SendSmsForm
# Create your views here.


# conn = redis.Redis(host='192.168.31.103', port=6379, password='123456', encoding='utf-8')

# 使用连接池连接redis
# pool = redis.ConnectionPool(host='192.168.31.103', port=6379, password='123456', encoding='utf-8', max_connections=1000)
# conn = redis.Redis(connection_pool=pool)

# 使用django_redis连接
# conn = get_redis_connection('default')


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过之后，写入数据库(密码要是密文)
        instance = form.save()

        # 创建交易记录
        # 方式一
        policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            policy_object=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),
        )

        # 方式二：使用中间件中的方式二，此处不做任何操作

        return JsonResponse({'status': True, 'href': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})
    # form = RegisterSubmitForm(request, data=request.POST)
    # if form.is_valid():
    #     return JsonResponse({'status': True})
    # return JsonResponse({'status': False, 'error': form.errors})


def send_check_code(request):
    # template = request.GET.get('template')
    # mobile_phone = request.GET.get('mobile_phone')
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})

    # template_code = settings.TEMPLATE_CODE.get(template)
    # if not template_code:
    #     return HttpResponse('模板不存在')
    # # template_code = 'SMS_154950909'  # 测试专用
    # check_code = random.randrange(100000, 999999)
    # result = send_sms(mobile_phone, settings.SIGN_NAME, template_code, "{'code': '" + str(check_code) + "'}")
    # result = json.loads(str(result, encoding='utf-8'))
    # print(result)
    # if result['Code'] == 'OK':
    #     return HttpResponse('成功')
    # else:
    #     return HttpResponse(result['Message'])


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'web/login_sms.html', {'form': form})
    form = LoginSmsForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确登录成功
        mobile_phone = form.cleaned_data['mobile_phone']
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60*60*24*14)
        return JsonResponse({'status': True, 'href': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def image_code(request):
    """生成图片验证码"""

    from utils.check_code.check_code import check_code

    image_object, code = check_code()

    request.session['image_code'] = code
    request.session.set_expiry(60)

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue(), content_type='image')


def login(request):
    """用户名和密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        email_or_phone = form.cleaned_data['username']
        password = form.cleaned_data['password']
        from django.db.models import Q
        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        exists = models.UserInfo.objects.filter(Q(email=email_or_phone) | Q(mobile_phone=email_or_phone)).exists()
        if not exists:
            form.add_error('username', '用户名不存在')
        else:
            user_object = (models.UserInfo.objects
                           .filter(Q(email=email_or_phone) | Q(mobile_phone=email_or_phone))
                           .filter(password=password).first())
            if user_object:
                request.session['user_id'] = user_object.id
                request.session.set_expiry(60*60*24*14)
                return redirect('index')
        form.add_error('password', '密码错误')
    return render(request, 'web/login.html', {'form': form})


def logout(request):
    request.session.flush()
    return redirect('index')
